using MediatR;
using TerritoryGame.Application.Queries;
using TerritoryGame.Domain.Repositories;

namespace TerritoryGame.Application.Handlers.QueryHandlers;

public class GetGameStatsQueryHandler : IRequestHandler<GetGameStatsQuery, GetGameStatsResult>
{
    private readonly IGameRepository _gameRepository;
    
    public GetGameStatsQueryHandler(IGameRepository gameRepository)
    {
        _gameRepository = gameRepository;
    }
    
    public async Task<GetGameStatsResult> Handle(GetGameStatsQuery request, CancellationToken cancellationToken)
    {
        try
        {
            var game = await _gameRepository.GetByIdAsync(request.GameId);
            if (game == null)
            {
                return new GetGameStatsResult
                {
                    Success = false,
                    ErrorMessage = "游戏不存在"
                };
            }
            
            var totalPixels = game.Canvas.Pixels.Count;
            var duration = 0;
            if (game.Room.StartTime.HasValue)
            {
                var endTime = game.Room.Status == Domain.Entities.GameStatus.Finished 
                    ? game.Room.UpdatedAt 
                    : DateTime.UtcNow;
                duration = (int)(endTime - game.Room.StartTime.Value).TotalSeconds;
            }
            
            // 计算玩家统计信息
            var playerStats = new List<PlayerStatsInfo>();
            var playerPixels = game.Canvas.Pixels
                .GroupBy(p => p.Value)
                .ToDictionary(g => g.Key, g => g.Count());
            
            var sortedPlayers = game.Room.Players
                .OrderByDescending(p => playerPixels.GetValueOrDefault(p.Color, 0))
                .ToList();
            
            for (int i = 0; i < sortedPlayers.Count; i++)
            {
                var player = sortedPlayers[i];
                var pixelCount = playerPixels.GetValueOrDefault(player.Color, 0);
                
                playerStats.Add(new PlayerStatsInfo
                {
                    Id = player.Id,
                    NickName = player.NickName,
                    Color = player.Color.Value,
                    TotalPixels = pixelCount,
                    PaintActions = 0, // TODO: 从事件日志中获取
                    AverageBrushSize = 1.0, // TODO: 从事件日志中计算
                    ActiveTime = TimeSpan.FromSeconds(duration), // TODO: 从事件日志中计算
                    Rank = i + 1
                });
            }
            
            var winner = playerStats.FirstOrDefault();
            
            var gameStats = new GameStatsInfo
            {
                GameId = game.Id,
                RoomName = game.Room.Name,
                CreatedAt = game.CreatedAt,
                StartTime = game.Room.StartTime,
                EndTime = game.Room.Status == Domain.Entities.GameStatus.Finished ? game.Room.UpdatedAt : null,
                Duration = duration,
                TotalPixels = totalPixels,
                PlayerStats = playerStats,
                Winner = winner
            };
            
            return new GetGameStatsResult
            {
                Success = true,
                GameStats = gameStats
            };
        }
        catch (Exception ex)
        {
            return new GetGameStatsResult
            {
                Success = false,
                ErrorMessage = $"获取游戏统计失败: {ex.Message}"
            };
        }
    }
}
